package com.seu.githubcn.config;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.seu.githubcn.entity.User;
import com.seu.githubcn.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Profile("!no-auth")
public class AuthFilterBean extends FilterRegistrationBean<Filter> {

    @Autowired
    UserMapper userMapper;

    @Override
    public Filter getFilter() {
        return new AuthFilter();
    }

    @WebFilter({"/user/renew", "/repo/*"})
    class AuthFilter implements Filter {

        @Override
        public void doFilter(
                ServletRequest request,
                ServletResponse response,
                FilterChain chain)
                throws IOException, ServletException {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            Integer userId = (Integer) httpServletRequest.getSession().getAttribute("userId");
            if (userId == null || !userMapper.exists(Wrappers.<User>lambdaQuery().eq(User::getUserId, userId))) {
//                httpServletResponse.setContentType("application/json;charset=UTF-8");
//                try (PrintWriter writer = new PrintWriter(httpServletResponse.getWriter())) {
//                    writer.write(mapper.writeValueAsString(Result.error(HttpServletResponse.SC_FORBIDDEN, "没有登录")));
//                }
//                ObjectMapper mapper = new ObjectMapper();
//                httpServletResponse.sendError(
//                        HttpServletResponse.SC_FORBIDDEN,
//                        mapper.writeValueAsString(Result.error(HttpServletResponse.SC_FORBIDDEN, "没有登录"))
//                );
                httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                chain.doFilter(request, response);
            }
        }
    }
}
